import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:get/get.dart';
import 'package:joyagoo/pages/widget/JoyEmptyWidget.dart';
import 'package:joyagoo/pages/widget/JoyProductHotCardWidget.dart';
import 'package:joyagoo/pages/widget/Joy_NoNetworkTip_Widget.dart';
import '../config/app_colors.dart';
import '../config/app_url_address.dart';
import '../model/productHotListModel.dart';
import '../utils/JoyActionService.dart';
import '../utils/JoyBlocUtil.dart';
import '../utils/JoyCacheManager.dart';
import '../utils/route_utils.dart';
import '../utils/currency_manager.dart';
import '../utils/CountdownManager.dart';
import '../utils/category_manager.dart';
import 'joy_home_bloc.dart';
import 'joy_hot_product_page.dart';
import 'joy_search_page.dart';
import 'joy_search_result_page.dart';
import 'joy_category_content_page.dart';
import 'widget/joy_product_card_widget.dart';
import 'widget/currency_selector_dialog.dart';
import 'widget/joy_top_widget.dart';

class JoyHomePage extends StatefulWidget {
  const JoyHomePage({super.key});

  @override
  State<JoyHomePage> createState() => _JoyHomePageState();
}

class _JoyHomePageState extends State<JoyHomePage>
    with TickerProviderStateMixin {
  late EasyRefreshController _refreshController;
  late PageController _bannerController;
  late AnimationController _animationController;
  int _currentBannerIndex = 0;
  final TextEditingController _searchController = TextEditingController();
  final CountdownManager _countdownManager = CountdownManager();
  Timer? _versionCheckTimer; // 版本检查定时器
  

  // 🔥 使用全局分类管理器，不再需要硬编码的分类数据
  // final List<Map<String, dynamic>> _categories = [
  //   {'name': 'JORDAN', 'image': 'images/JORDAN.png'},
  //   {'name': 'Ralph Lauren', 'image': 'images/Ralph Lauren.png'},
  //   {'name': 'T-shirt', 'image': 'images/T-shirt.png'},
  //   {'name': 'Dior B22', 'image': 'images/Dior B22.png'},
  //   {'name': 'Goyard wallet', 'image': 'images/Group 80.png'},
  //   {'name': 'NIKE', 'image': 'images/NIKE.png'},
  //   {'name': 'ADIDAS', 'image': 'images/ADIDAS.png'},
  // ];
  
  List<Map<String, dynamic>> _products = [];
  bool _isLoading = false;

  int pageSize = 10;
  int pageNo = 1;

  late JoyHomeBloc homeBloc;

  String error_acl = "No Data";
  bool isNetError_acl = false;
  String errorImage_acl = "";
  bool isError = false;

  List bannerImagesMap = [
  ];
  List _bannerImages = [
  ];

  List hotProductList = [
  ];
  // 添加选中的分类索引
  int _selectedCategoryIndex = 0;
  
  // 当前货币
  String _currentCurrency = 'USD,\$';

  @override
  void initState() {
    super.initState();
    _refreshController = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
    _bannerController = PageController();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    _loadInitialData();
    _startBannerAutoPlay();
    _initializeCurrency();
    _initializeCountdownManager();
    
    // 页面初始化2秒后执行版本检查
    _versionCheckTimer = Timer(const Duration(seconds: 2), () {
      if (mounted) {
        debugPrint("执行版本检查...");
        JoyActionService.LitVersionInfo(context);
      }
    });
  }
  
  // 初始化货币管理器
  void _initializeCurrency() async {
    await CurrencyManager.instance.initialize();
    setState(() {
      _currentCurrency = CurrencyManager.instance.formattedCurrencyDisplay;
    });
  }

  // 初始化倒计时管理器
  void _initializeCountdownManager() {
    // 启动全局倒计时管理器
    _countdownManager.startGlobalCountdown();
  }
  
  // 显示货币选择器
  void _showCurrencySelector() {
    CurrencyDialogHelper.showCurrencySelector(
      context,
      onCurrencySelected: (currency) async {
        await CurrencyManager.instance.setCurrency(currency);
        setState(() {
          _currentCurrency = '${currency.code},${currency.symbol}';
        });
        
        // 货币改变后刷新首页数据
        _refreshHomeData();
      },
    );
  }

  // 刷新首页数据
  void _refreshHomeData() {
    // 重置页码
    pageNo = 1;
    
    // 刷新热门商品列表
    homeBloc.add(GetJOYHotProductListEvent(context, pageNo, pageSize, false));
    
    // 刷新首页横幅和产品数据
    homeBloc.add(GetJOYHomeDataBannerAndProductEvent(context, appHomeType));
    
    // 🔥 货币切换时检查分类数据（仅在没有数据或数据过期时刷新）
    if (!CategoryManager.instance.hasCategories || CategoryManager.instance.isDataExpired) {
      debugPrint("CategoryManager: 货币切换 - 分类数据缺失或过期，重新获取");
      homeBloc.add(GetJOYHomeCategoryEvent(context, appHomeType, ""));
    } else {
      debugPrint("CategoryManager: 货币切换 - 分类数据存在且未过期，跳过请求");
    }
    
    // 显示刷新提示（防重复）
    if (CurrencyManager.shouldShowNotification()) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Currency updated, refreshing data...'),
          backgroundColor: Color(0xFFFF6B35),
          duration: Duration(seconds: 2),
        ),
      );
    }
  }
  
  @override
  void dispose() {
    _refreshController.dispose();
    _bannerController.dispose();
    _animationController.dispose();
    _searchController.dispose();
    _countdownManager.dispose();
    _versionCheckTimer?.cancel(); // 清理版本检查定时器
    super.dispose();
  }
  
  void _startBannerAutoPlay() {
    Future.delayed(const Duration(seconds: 3), () {
      if (mounted && _bannerController.hasClients) {
        _currentBannerIndex = (_currentBannerIndex + 1) % _bannerImages.length;
        _bannerController.animateToPage(
          _currentBannerIndex,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeInOut,
        );
        _startBannerAutoPlay();
      }
    });
  }
  
  void _loadInitialData() {
    // 模拟初始数据加载
    _products = List.generate(10, (index) => {
      'id': index,
      'title': 'Fashion Item ${index + 1}',
      'price': '\$${(50 + index * 10).toStringAsFixed(2)}',
      'originalPrice': '\$${(80 + index * 15).toStringAsFixed(2)}',
      'discount': '${10 + index * 2}%',
      'image': 'https://images.unsplash.com/photo-${1500000000000 + index}?w=400',
      'rating': 4.0 + (index % 5) * 0.2,
      'isNew': index < 3, // 前3个商品标记为新品
    });
  }
  
  Future<void> _onRefresh() async {
    pageNo = 1;
    homeBloc.add(GetJOYHotProductListEvent(context,pageNo,pageSize,false));
    
    // 🔥 刷新时检查分类数据是否需要更新（仅在数据过期时刷新）
    if (CategoryManager.instance.isDataExpired) {
      debugPrint("CategoryManager: 下拉刷新 - 分类数据已过期，重新获取");
      homeBloc.add(GetJOYHomeCategoryEvent(context, appHomeType, ""));
    } else {
      debugPrint("CategoryManager: 下拉刷新 - 分类数据未过期，跳过请求");
    }
  }
  
  Future<void> _onLoad() async {
    pageNo = pageNo + 1;
    homeBloc.add(GetJOYHotProductListEvent(context,pageNo,pageSize,false));
  }
  
  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle(
        statusBarColor: AppColors.backHomeYellowGround, // 设置状态栏背景颜色为黄色
        statusBarIconBrightness: Brightness.dark, // 状态栏图标为深色
        statusBarBrightness: Brightness.light, // iOS 状态栏样式
      ),
      child: Scaffold(
        backgroundColor: AppColors.backgroundSecondary,
        body: BLocMain()
      ),
    );
  }


  Widget BLocMain(){
    return JoyBlocUtil.getAppNoBarBloc(builder: (context, state) {
      return buildMain();
    }, create: (_) {
      homeBloc = JoyHomeBloc();
      homeBloc.add(GetJOYHomeDataBannerAndProductEvent(context,appHomeType));
      homeBloc.add(GetJOYHotProductListEvent(context,pageNo,pageSize,false));
      
      // 🔥 获取分类数据并存储到全局管理器（仅在没有数据或数据过期时）
      if (!CategoryManager.instance.hasCategories || CategoryManager.instance.isDataExpired) {
        debugPrint("CategoryManager: 首次加载 - 获取分类数据");
        homeBloc.add(GetJOYHomeCategoryEvent(context, appHomeType, ""));
      } else {
        debugPrint("CategoryManager: 分类数据已存在且未过期，跳过请求");
      }

      return homeBloc;
    }, buildWhen: (previousState, state) {
      if(state is GetJOYHomeDataBannerAndProductEventSuccess){
        isNetError_acl = false;
        Map result  = state.data;
        _bannerImages = result["homeImages"]??[];
        debugPrint("Banner images loaded: $_bannerImages");
        for (int i = 0; i < _bannerImages.length; i++) {
          debugPrint("Banner $i URL: ${joypictureBannerUrl}${_bannerImages[i]}");
        }
        bannerImagesMap = result["categoryJson"]??[];
        // List productMap = result["hotProduct"]??[];
        // hotProductList = List<ProductModel>.from(productMap.map((x) => ProductModel.fromJson(x)));
        return true;

      }
      if(state is GetJOYHomeDataBannerAndProductEventFailure){
        isNetError_acl = true;
        String message = state.errMsg??"Request failed";
        error_acl = message;
        return true;
      }
      if(state is GetJOYHotProductListEventSuccess){
        isNetError_acl = false;
        Map result  = state.data;
        debugPrint("GetALCHotProductListEventSuccess == $result");
        // bannerImages = result["homeImages"]??[];
        // bannerImagesMap = result["categoryJson"]??[];
        List productMap = result["records"]??[];
        debugPrint("GetALCHotProductListEventSuccess2 == $productMap");

        List hotProductListData = List<ProductHotModel>.from(productMap.map((x) => ProductHotModel.fromJson(x)));
        debugPrint("GetALCHotProductListEventSuccess2 == $hotProductList");
        if(pageNo == 1){
          hotProductList.clear();
          hotProductList.addAll(hotProductListData);
        }else{
          hotProductList.addAll(hotProductListData);
        }
        _refreshController.resetHeader();
        _refreshController.finishLoad();
        _refreshController.finishRefresh();
        _refreshController.resetFooter();
        if(hotProductListData.length < pageSize){
          _refreshController.finishLoad(IndicatorResult.noMore);
        }else{
          _refreshController.finishLoad();
          _refreshController.resetFooter();

        }

        if(hotProductList.isEmpty){
          error_acl = "No results found";
        }
        return true;
      }

      if(state is GetJOYHotProductListEventFailure){
        isNetError_acl = true;
        String message = state.errMsg??"Request failed";
        error_acl = message;
        pageNo = pageNo - 1;
        if(pageNo <= 0){
          pageNo = 1;
        }
        _refreshController.finishLoad();
        _refreshController.finishRefresh();
        _refreshController.resetHeader();
        _refreshController.resetFooter();

        return true;

      }
      
      // 🔥 处理分类数据获取成功事件
      if(state is GetJOYHomeCategoryEventSuccess){
        debugPrint("GetJOYHomeCategoryEvent分类数据获取成功");
        // 分类数据已经在BLoC中自动保存到全局管理器
        // 这里可以做一些额外的处理，比如刷新UI等
        return true;
      }
      
      if(state is GetJOYHomeCategoryEventFailure){
        debugPrint("GetJOYHomeCategoryEvent分类数据获取失败: ${state.errMsg}");
        // 分类数据获取失败时的处理
        return false;
      }

      return false;
    });
  }

  Widget errornetwork(){
    return Padding(padding: EdgeInsets.only(left: 0.w,right: 0.w),
      child: JoyNoNetworkTipWidget(
        haveNetWorkCallBack: (){
          debugPrint("网络已恢复，开始刷新首页数据");
          
          // 🔥 网络恢复时自动刷新数据（不仅限于错误状态）
          pageNo = 1;
          homeBloc.add(GetJOYHomeDataBannerAndProductEvent(context,appHomeType));
          homeBloc.add(GetJOYHotProductListEvent(context,pageNo,pageSize,false));
          
          // 🔥 网络恢复时检查分类数据（仅在没有数据或数据过期时获取）
          if (!CategoryManager.instance.hasCategories || CategoryManager.instance.isDataExpired) {
            debugPrint("CategoryManager: 网络恢复 - 需要获取分类数据");
            homeBloc.add(GetJOYHomeCategoryEvent(context, appHomeType, ""));
          } else {
            debugPrint("CategoryManager: 网络恢复 - 分类数据存在且未过期，跳过请求");
          }
          
          // 重置错误状态
          this.isError = false;
          isNetError_acl = false;
        },
        noNetWorkCallBack: (){
          debugPrint("网络已断开，设置错误状态");
          this.isError = true;
        },
      ),
    );
  }

  Widget ShowEmpty(){
    final double statusBarHeight = MediaQuery.of(context).padding.top;
    return Column(
      children: [
        Container(
          height: statusBarHeight,
        ),
        errornetwork(),
        Expanded(
          child:  JoyEmptyWidget(messageError: error_acl, isNetError: isNetError_acl, errorImagePath: "",isShowBtn: true, tapOnCallBack: (){
            pageNo = 1;
            homeBloc.add(GetJOYHomeDataBannerAndProductEvent(context,appHomeType));
            homeBloc.add(GetJOYHotProductListEvent(context,pageNo,pageSize,false));
            
            // 🔥 空状态重试时检查分类数据（仅在没有数据时重新获取）
            if (!CategoryManager.instance.hasCategories) {
              debugPrint("CategoryManager: 空状态重试 - 无分类数据，重新获取");
              homeBloc.add(GetJOYHomeCategoryEvent(context, appHomeType, ""));
            } else {
              debugPrint("CategoryManager: 空状态重试 - 已有分类数据，跳过请求");
            }
          }),
        )
      ],
    );
  }


  Widget buildMain(){


    if(isNetError_acl == true && hotProductList.isEmpty){
      return ShowEmpty();
    }

    return NestedScrollView(
      headerSliverBuilder: (context, innerBoxIsScrolled) {
        return [

          SliverAppBar(
            floating: true,
            pinned: false,
            snap: true,
            backgroundColor: Colors.transparent,
            elevation: 0,
            toolbarHeight: 108.h,
            flexibleSpace: ClipRRect(
              borderRadius: BorderRadius.only(
                bottomLeft: Radius.circular(8.r),
                bottomRight: Radius.circular(8.r),
              ),
              child: Container(
                decoration: BoxDecoration(
                  color: AppColors.backHomeYellowGround,
                ),
                child: SafeArea(
                  child: Column(
                    children: [
                      // 顶部组件
                      JoyTopWidget(
                        onCurrencyChanged: _refreshHomeData,
                      ),
                      // 🔥 优化后的紧凑布局：宣传语 + 搜索框
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 4.h),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.start, // 🔥 从上到下紧凑排列
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // 宣传语
                            Text(
                              "Welcome to LitBuy Sheets".tr,
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                color: AppColors.primaryVariant,
                                fontSize: 18.sp,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                           
                            // 🔥 宣传语和搜索框之间的紧凑间距
                            SizedBox(height: 6.h),
                            // 搜索框
                            searchWidget(),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
          // 黄色区域和下方内容的间距
          SliverToBoxAdapter(
            child: SizedBox(height: 6.h),
          ),
          SliverList(
            delegate: SliverChildListDelegate([
              errornetwork(),
            ]),
          ),
          // 错误提示和Banner之间的间距
          SliverToBoxAdapter(
            child: SizedBox(height: 6.h),
          ),
          // Banner轮播图
          SliverList(
            delegate: SliverChildListDelegate([
              _buildBannerSection(),
            ]),
          ),
        ];
      },
      body: EasyRefresh(
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoad: _onLoad,
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 推荐商品
              _buildProductsSection(),
            ],
          ),
        ),
      ),
    );
  }

  Widget searchWidget(){
    return InkWell(
      child:   Container(
        height: 40.h,
                        decoration: BoxDecoration(
                          color: AppColors.backgroundSearch,
                          borderRadius: BorderRadius.circular(10),
                        ),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center, // 🔥 确保Row内所有元素垂直居中
                          children: [
                            Expanded(
                              child: TextField(
                                enabled: false,
                                controller: _searchController,
                                textAlign: TextAlign.left, // 🔥 文本左对齐（搜索框常见样式）
                                decoration: InputDecoration(
                                  hintText: 'Search within the app',
                                  hintStyle: TextStyle(
                                    color: AppColors.textHint,
                                    fontSize: 13.sp,
                                  ),
                                  border: InputBorder.none,
                                  contentPadding: EdgeInsets.symmetric(
                                    horizontal: 16.w,
                                    vertical: 10.h, // 🔥 增加垂直内边距，让文本在搜索框中垂直居中
                                  ),
                                ),
                              ),
                            ),
                           SizedBox(width: 8.w), // 🔥 减少间距，使用响应式单位
                            // 🔥 相机图标容器 - 添加居中对齐
                            Container(
                              width: 35.w,
                              height: 35.w,
                              child: Center( // 🔥 图标在容器内居中
                                child: Icon(
                                  Icons.camera_alt,
                                  color: AppColors.primaryVariant,
                                  size: 20.sp,
                                ),
                              ),
                            ),
                            SizedBox(width: 8.w), // 🔥 添加间距
                           // 🔥 搜索图标容器 - 添加居中对齐
                           Container(
                                width: 35.w,
                                height: 35.w,
                                decoration: BoxDecoration(
                                  color: AppColors.primaryVariant,
                                  borderRadius: BorderRadius.circular(15.w),
                                ),
                                child: Center( // 🔥 图标在容器内居中
                                  child: Icon(
                                    Icons.search,
                                    color: AppColors.buttonTextPrimary,
                                    size: 15.sp,
                                  ),
                                ),
                              ),
                              SizedBox(width: 8.w), // 🔥 右侧边距
                            
                          ],
                        ),
                      ),
      onTap: (){
              JoyNavUtils().to(JoySearchPage());
      },
    );

  }
  
  Widget _buildBannerSection() {
    // 计算banner的自适应高度，保持宽高比358:126 (2.841:1)
    final screenWidth = MediaQuery.of(context).size.width;
    final availableWidth = screenWidth - 20.w; // 减去左右各10.w的margin
    final bannerHeight = availableWidth / 2.841269841269841; // 根据宽高比358:126计算高度
    
    return Container(
      height: bannerHeight,
      width: double.infinity,
      child: Stack(
        children: [
         
          Container(
            margin: EdgeInsets.symmetric(horizontal: 10.w),
            child: PageView.builder(
              controller: _bannerController,
              onPageChanged: (index) {
                setState(() {
                  _currentBannerIndex = index;
                });
              },
              itemCount: _bannerImages.length,
              itemBuilder: (context, index) {
                return GestureDetector(
                  onTap: () {
                    print('Banner点击: $index');
                    _handleBannerTap(index);
                  },
                  child: Material(
                    elevation: 4, // 阴影高度
                    borderRadius: BorderRadius.circular(12.r),
                    shadowColor: Colors.black.withOpacity(0.1),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(12.r),
                      child: _buildNetworkImage("${_bannerImages[index]}"),
                    ),
                  ),
                );
              },
            ),
          ),
          // 指示器
          Positioned(
            bottom: 16.h,
            left: 0,
            right: 0,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: _bannerImages.asMap().entries.map((entry) {
                return Container(
                  width: 8.w,
                  height: 8.h,
                  margin: EdgeInsets.symmetric(horizontal: 4.w),
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: _currentBannerIndex == entry.key
                        ? AppColors.textWhite
                        : AppColors.withOpacity(AppColors.textWhite, 0.4),
                  ),
                );
              }).toList(),
            ),
          ),
        ],
      ),
    );
  }
  
  Widget _buildCategorySection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 10.w),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                'Categories',
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.bold,
                  color: AppColors.textPrimary,
                ),
              ),
            ],
          ),
        ),
        SizedBox(height: 8.h),
        // 🔥 使用Obx监听全局分类数据变化，UI会自动更新
        Obx(() {
          final categoryManager = CategoryManager.instance;
          
          // 如果正在加载分类数据
          if (categoryManager.isLoading) {
            return Container(
              height: 30.w,
              child: Center(
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFFF6B35)),
                ),
              ),
            );
          }
          
          // 如果没有分类数据
          if (!categoryManager.hasCategories) {
            return Container(
              height: 30.w,
              padding: EdgeInsets.symmetric(horizontal: 10.w),
              child: Center(
                child: Text(
                  'No categories available',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: AppColors.textHint,
                  ),
                ),
              ),
            );
          }
          
          // 显示分类列表
          final categories = categoryManager.categories;
          return Container(
            height: 40.w,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              padding: EdgeInsets.symmetric(horizontal: 10.w),
              itemCount: categories.length,
              itemBuilder: (context, index) {
                final category = categories[index];
                return GestureDetector(
                  onTap: () {
                    debugPrint('分类点击: ${category.categoryName}');
                    setState(() {
                      _selectedCategoryIndex = index;
                    });
                    // 🔥 跳转到分类内容页面，展示该分类下的所有子分类和商品
                    JoyNavUtils().to(JoyCategoryContentPage(
                      fromHome: true,
                      categoryName: category.categoryName,
                      categoryId: category.categoryId.toString(),
                    ));
                  },
                  child: Container(
                    margin: EdgeInsets.only(right: 6.w),
                    padding: EdgeInsets.symmetric(
                      horizontal: 16.w, // 🔥 增加水平内边距，让文本更好居中
                      vertical: 6.h,   // 🔥 增加垂直内边距，让文本更好居中
                    ),
                    decoration: BoxDecoration(
                      color: index == _selectedCategoryIndex 
                          ? AppColors.primaryVariant
                          : AppColors.background,
                      borderRadius: BorderRadius.circular(16.w),
                      border: Border.all(
                        color: index == _selectedCategoryIndex 
                            ? AppColors.primaryVariant
                            : AppColors.border,
                      ),
                    ),
                    // 🔥 使用Center widget确保文本在容器中完全居中
                    child: Center(
                      child: Text(
                        category.categoryName,
                        textAlign: TextAlign.center, // 🔥 文本对齐方式居中
                        style: TextStyle(
                          color: index == _selectedCategoryIndex 
                              ? AppColors.textWhite 
                              : AppColors.textPrimary,
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ),
                );
              },
            ),
          );
        }),
      ],
    );
  }

  // 处理Banner点击事件
  void _handleBannerTap(int index) {
    debugPrint('Clicked Banner ${index + 1}');
    // Navigate to different pages based on different banners

    String url = "${_bannerImages[index]}";
    debugPrint('Clicked Banner url = $url');

    String searchCategory = "";
    
    // 🔥 使用全局分类管理器查找匹配的分类
    final categories = CategoryManager.instance.categories;
    for (var category in categories) {
      String categoryName = category.categoryName;
      if(url.toLowerCase().contains(categoryName.toLowerCase())){
        searchCategory = categoryName;
  
        // 特殊分类名称映射
        if(categoryName == "Sweater") {
          searchCategory = "Hoodie/Sweater";
        }

        break;
        
      }
    }
    
    if(searchCategory.isNotEmpty){
      JoyNavUtils().to(JoySearchResultPage(searchword: searchCategory, isSearch: false));
    } else {
      // 如果没有找到匹配的分类，跳转到Discord
      JoyActionService.LitaunchDiscordApp('https://discord.gg/qdyjDrhhS5');
    }
  }
  
  Widget _buildProductsSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 5.h),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                'Discounted Products',
                style: TextStyle(
                  fontSize: 16.sp,
                  color: Colors.black,
                  fontWeight: FontWeight.bold,
                ),
              ),
              //
              // InkWell(
              //   child: Text(
              //     'more',
              //     style: TextStyle(
              //       fontSize: 20.sp,
              //       color: Colors.black,
              //       fontWeight: FontWeight.bold,
              //     ),
              //   ),
              //   onTap: (){
              //     JoyNavUtils().to(JoyHotProductPage());
              //   },
              // )
            ],
          )
        ),
        SizedBox(height: 8.h),
        GridView.builder(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          padding: EdgeInsets.symmetric(horizontal: 12.w),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            crossAxisSpacing: 12.w,
            mainAxisSpacing: 12.h,
            childAspectRatio: 0.65,
          ),
          itemCount: hotProductList.length,
          itemBuilder: (context, index) {
            ProductHotModel product = hotProductList[index];
            return JoyProductHotCardWidget(
              productModel: product,
              onTap: () {
                // print('商品点击: ${product['title']}');
              },
              onFavorite: () {
                // print('收藏: ${product['title']}');
              },
            );
          },
        ),
        // if (_isLoading)
        //   Padding(
        //     padding: EdgeInsets.all(16.w),
        //     child: Center(
        //       child: CircularProgressIndicator(),
        //     ),
        //   ),
        // SizedBox(height: 20.h),
      ],
    );
  }

  // 新的网络图片加载方法
  Widget _buildNetworkImage(String imageUrl) {
    return FadeInImage(
      placeholder: MemoryImage(_createPlaceholderImage()),
      image: NetworkImage(imageUrl),
      fit: BoxFit.cover,
      fadeInDuration: const Duration(milliseconds: 300),
      fadeOutDuration: const Duration(milliseconds: 100),
      imageErrorBuilder: (context, error, stackTrace) {
        return Container(
          color: AppColors.backgroundSecondary,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.image_not_supported,
                size: 48.sp,
                color: AppColors.textHint,
              ),
              SizedBox(height: 8.h),
              Text(
                'Image loading failed',
                style: TextStyle(
                  fontSize: 12.sp,
                  color: AppColors.textHint,
                ),
              ),
              SizedBox(height: 8.h),
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    // 触发重新构建来重试加载图片
                  });
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppColors.primary,
                  padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
                ),
                child: Text(
                  'Retry',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.white,
                  ),
                ),
              ),
            ],
          ),
        );
      },
      placeholderErrorBuilder: (context, error, stackTrace) {
        return Container(
          color: Colors.grey[200],
          child: Center(
            child: CircularProgressIndicator(
              strokeWidth: 2,
              valueColor: AlwaysStoppedAnimation<Color>(
                AppColors.textHint,
              ),
            ),
          ),
        );
      },
    );
  }

  // 创建占位图片的字节数据
  Uint8List _createPlaceholderImage() {
    // 创建一个简单的1x1像素的透明图片
    return Uint8List.fromList([
      0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D,
      0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
      0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00,
      0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00,
      0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49,
      0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82
    ]);
  }
}